package com.sfac.hqyj.springBoot.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebListener
public class LogFileDestroyListener implements ServletContextListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogFileDestroyListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("==== Init LogFileDestroyListener ====");

        File logFolder = new File("/log");
        if (!logFolder.exists()) {
            return;
        }

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = dtf.format(LocalDateTime.now());

        File[] files = logFolder.listFiles();
        for (File file : files) {
            if (!file.getName().contains(currentDate)) {
                file.delete();
            }
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("==== Destroyed LogFileDestroyListener ====");
    }
}
